package com.sinosoft.vaccinetoai.log;

import com.sinosoft.vaccinetoai.exception.BusinessException;
import com.sinosoft.vaccinetoai.exception.ExceptionEnums;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * 接口日志AOP
 * @author xzh
 * @date 2022-10-24 14:12
 * @since 5.0.0
 */
@Slf4j
@Order(5)
@Aspect
@Component
public class ControllerLogAop {

    private static final String POINT_CUT = "execution (* com.sinosoft.vaccinetoai..*.controller.*.*(..))";

    /**
     * 环绕处理
     * @param pjp 连接点
     * @return {@link Object }
     * @throws Throwable 异常
     * @author xzh
     * @since 5.0.0
     */
    @Around(POINT_CUT)
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        //方法返参
        Object result = null;

        log.info("---------- {}.{} <-> start ----------", pjp.getTarget().getClass().getSimpleName(), pjp.getSignature().getName());

        //方法参数
        Object[] args = pjp.getArgs();
        for(Object obj : pjp.getArgs())
            log.debug("params:\t\t" + ((obj != null) ? obj.toString() : ""));

        //开始执行时间戳
        long start = System.currentTimeMillis();
        try {
            result = pjp.proceed(args);
        } catch(BusinessException e) {
            throw e;
        } catch(Exception e) {
            log.error("controller error", e);
            throw BusinessException.ofExceptionEnums(ExceptionEnums.ERROR);
        } finally {
            //结束执行时间戳
            long end = System.currentTimeMillis();
            log.info("---------- {}.{} <-> end {}ms ----------", pjp.getTarget().getClass().getSimpleName(), pjp.getSignature().getName(), end - start);
        }
        return result;
    }

}
